package com.fingard.dsp.bank.directbank.dlcb01;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.xml.XmlTextWriter;

/**
 * 大连银行基础类
 * 
 * @author Cruise
 * @date 2018/11/05
 */
public class DLCB01Base extends DirectBase implements ITcpClient {
	/**
	 * 获取字符集
	 * 
	 * @return
	 */
	protected String getCharset() {
		return getBankConfig().getCharset("GBK");
	}

	/**
	 * 写通用报文头部
	 * 
	 * @param xmlWriter
	 * @param tmpBankHeader
	 */
	public void writeCommonHeader(XmlTextWriter xmlWriter, DLCB01Header tmpBankHeader) {
		xmlWriter.writeStartElement("ap");
		xmlWriter.writeStartElement("head");
		xmlWriter.writeElementString("tr_code", tmpBankHeader.trncode);
		xmlWriter.writeElementString("cms_corp_no", "");
		xmlWriter.writeElementString("user_no", "");
		xmlWriter.writeElementString("org_code", "");
		xmlWriter.writeElementString("serial_no", "");
		xmlWriter.writeElementString("req_no", tmpBankHeader.reqSeqNo);
		Date tmpDateNow = new Date();
		xmlWriter.writeElementString("tr_acdt", Format.Date8Format.format(tmpDateNow));
		xmlWriter.writeElementString("tr_time", Format.Time6Format.format(tmpDateNow));
		xmlWriter.writeElementString("channel", "5");
		xmlWriter.writeElementString("sign", "");
		xmlWriter.writeElementString("file_flag", tmpBankHeader.isFile);
		xmlWriter.writeElementString("Reserved1", "");
		xmlWriter.writeElementString("Reserved", "");
		xmlWriter.writeEndElement();
	}

	/**
	 * 发送银行 
	 * 
	 * @param tmpReqStr
	 * @return
	 * @throws Exception
	 */
	public String[] sendToBank(String tmpReqStr) throws Exception {
		String[] tmpStrRet = new String[] {"", ""};
		
		tmpReqStr = "00" + tmpReqStr;
		
		String tmpReqHeader = String.format("%10s", tmpReqStr.getBytes(getCharset()).length).replace(" ", "0");
		String tmpSendStr = tmpReqHeader + tmpReqStr;
		WriteBankLogStep2(tmpSendStr);
		
		WriteBankLogLn("2.提交银行的地址：" + bankFront.serverIP + ":" + bankFront.serverPort);
		
		TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
		TcpReceiver tmpReceiver = tmpClient.sendMessage(tmpSendStr.getBytes(getCharset()));
		
		tmpStrRet[0] = tmpReceiver.connState;
        if (tmpReceiver.recBytes != null) {
            tmpStrRet[1] = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, getCharset());
            if (tmpStrRet[1].indexOf("<") > 0) {
            	tmpStrRet[1] = tmpStrRet[1].substring(tmpStrRet[1].indexOf("<"));
            }
        } else {
            tmpStrRet[1] = tmpReceiver.getConnMsg();
        }
        WriteBankLogStep3(tmpStrRet[1]);
        if (!tmpReceiver.isCompleted) {
            WriteBankLogLn(tmpReceiver.getConnMsg());
        }
		
		return tmpStrRet;
	}

	/*// 获取文件夹目录下所有文件名
	List<String> getDirectoryAllFileName(String balanceFilePath) {
		List<String> fileNames = new ArrayList<String>();
		File file = new File(balanceFilePath);
		if (file.isDirectory()) {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				fileNames.add(files[i].getName());
			}
		}
		return fileNames;
	}

	protected FtpReceiver download(String filename, String childpath) throws IOException {
		FtpSet ftpSet = bankFront.getFtpSet("ftpserver");
		FtpPortClient ftpPtClient = new FtpPortClient(ftpSet);
		WriteBankLogLn("下载FINISH地址:" + ftpSet.serverIP + ":" + ftpSet.port + File.separator + ftpSet.downDir);
		String path = getDataFileDirectory(new Date());

		FtpReceiver ftpReceiver = ftpPtClient.downloadFile(filename, path + File.separator + childpath);
		return ftpReceiver;
	}*/
	
	public static int getCharacterPosition(String string, int index){
	    //这里是获取"|"符号的位置
	    Matcher slashMatcher = Pattern.compile("\\|").matcher(string);
	    int mIdx = 0;
	    while(slashMatcher.find()) {
	       mIdx++;
	       //当"|"符号第N次出现的位置
	       if(mIdx == index){
	          break;
	       }
	    }
	    return slashMatcher.start();
	}
	
	public static List<String> getResult(String str) throws Exception {
		List<String> list = new ArrayList<String>();
		for(int i = 1;i<str.length();i++) {
			int index = getCharacterPosition(str,16);
			String firstMsg = str.substring(0, index);
//			System.out.println("截取结果:"+firstMsg);
			list.add(firstMsg);
			str = str.substring(index+1);
		}
		return list;
		
		/*Iterator<String> lists = list.iterator();
		while(lists.hasNext()) {
			System.out.println("遍历结果:"+lists.next());
		}*/
	}

	@Override
	public void getContentLength(TcpReceiver p_receiver) throws Exception {
		if (p_receiver.contentLength == -1) {
			if (p_receiver.readedLength >= 10) {
				p_receiver.contentLength = Integer.parseInt(new String(p_receiver.recBytes, 0, 10, getCharset()));
				p_receiver.contentStartIndex = 10;
			}
		}
	}
}
